import {useEffect, useState} from "react";
import "./CourseSelection.css"
import axios from "axios";

function CourseSelection() {
    // 模拟课程数据
    const availableCourses = [
        { courseId: 1, courseName: "英语听力提高" },
        { courseId: 2, courseName: "高级阅读技能" },
        { courseId: 3, courseName: "写作技巧精讲" },
        { courseId: 4, courseName: "四级模拟测试" },
    ];

    const [selectedCourses, setSelectedCourses] = useState([]);
    const user = JSON.parse(localStorage.getItem('currentUser'));
    const userId = user ? user.userId : null;

    // 从后端获取可选课程
    useEffect(() => {
        // 获取已选课程
        const fetchSelectedCourses = async () => {
            try {
                const response = await axios.get(`/api/enrolled-courses/${userId}`);
                setSelectedCourses(response.data);
            } catch (error) {
                console.error("获取已选课程失败:", error);
            }
        };

        // 获取可选课程
        const fetchAvailableCourses = async () => {
            try {
                const response = await axios.get(`/api/available-courses/${userId}`);
                setAvailableCourses(response.data);
            } catch (error) {
                console.error("获取可选课程失败:", error);
            }
        };

        fetchSelectedCourses();
        fetchAvailableCourses();
    }, [userId]);


    // 处理选课逻辑
    const handleSelectCourse = async (courseId) => {
        try {
            // 调用后端选课 API
            const response = await axios.post(`/api/enroll-course/${userId}/${courseId}`);

            if (response.status === 200) {
                const message = response.data;

                // 更新已选课程
                const course = availableCourses.find((c) => c.courseId === courseId);
                if (course && !selectedCourses.some((c) => c.courseId === course.courseId)) {
                    setSelectedCourses((prevSelectedCourses) => [...prevSelectedCourses, course]);
                }

                // 根据后端返回的消息提示用户
                if (message === "课程已更新") {
                    alert("你已更新该课程的选课时间！");
                } else if (message === "选课成功") {
                    alert("选课成功！");
                }
            }
        } catch (err) {
            console.error("选课失败:", err);

            // 处理错误提示
            if (err.response) {
                alert(err.response.data || "选课失败，请稍后重试。");
            } else if (err.request) {
                alert("网络错误，请检查网络连接！");
            } else {
                alert("选课失败，原因：" + err.message);
            }
        }
    };
    // 删除选课逻辑
    const handleDeleteCourse = async (courseId) => {
        try {
            const courseToDelete = selectedCourses.find((course) => course.courseId === courseId);

            if (!courseToDelete) {
                alert("找不到该课程，无法删除！");
                return;
            }

            const enrollTime = new Date(courseToDelete.enrollTime);
            const now = new Date();
            const timeDifference = now - enrollTime;


            const response = await axios.delete(`/api/enroll-course/${userId}/${courseId}`);

            if (response.status === 200) {
                const updatedCourses = selectedCourses.filter(
                    (course) => course.courseId !== courseId
                );
                setSelectedCourses(updatedCourses);

                alert("课程已成功删除！");
            }
        } catch (err) {
            console.error("删除课程失败:", err);

            // 确保错误信息是字符串
            if (err.response) {
                const errorMessage = typeof err.response.data === "string"
                    ? err.response.data
                    : JSON.stringify(err.response.data); // 转换为字符串
                alert(errorMessage || "删除课程失败，请稍后重试。");
            } else if (err.request) {
                alert("网络错误，请检查网络连接！");
            } else {
                alert("删除课程失败，原因：" + err.message);
            }
        }
    };
    return (
        <div className="course-selection-container">
            <h2>选课界面</h2>
            <p>选择你感兴趣的课程：</p>

            {/* 可选课程列表 */}
            <div className="available-courses">
                <h3>可选课程</h3>
                {availableCourses.map((course) => (
                    <div key={course.courseId} className="course-item">
                        <span>{course.courseName}</span>
                        <button
                            onClick={() => handleSelectCourse(course.courseId)}
                            disabled={selectedCourses.some(
                                (c) => c.courseId === course.courseId
                            )}
                            className="select-course-button"
                        >
                            {selectedCourses.some(
                                (c) => c.courseId === course.courseId
                            )
                                ? "已选"
                                : "选课"}
                        </button>
                    </div>
                ))}
            </div>

            {/* 已选课程 */}
            <div className="selected-courses">
                <h3>已选课程</h3>
                {selectedCourses.length === 0 ? (
                    <p>你还没有选择任何课程。</p>
                ) : (
                    <ul>
                        {selectedCourses.map((course) => (
                            <li key={course.courseId}>
                                {course.courseName}
                                <button
                                    onClick={() => handleDeleteCourse(course.courseId)}
                                    className="delete-course-button"
                                >
                                    删除
                                </button>
                            </li>
                        ))}
                    </ul>
                )}
            </div>
        </div>
    );
}

export default CourseSelection;